package com.softaria.gwt.common.client;

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Timer;

/**
 * A <code>Timer</code> that is canceled if a new request is made.
 */
public class DelayedTask {

  private Timer timer;
  private Command listener;

  /**
   * Creates a new delayed task.
   * 
   * @param listener
   *          the listener to be called
   */
  public DelayedTask(final Command listener) {
    this.listener = listener;
  }

  /**
   * Cancels the task.
   */
  public void cancel() {
    if (timer != null) {
      timer.cancel();
    }
  }

  /**
   * Cancels any running timers and starts a new one.
   * 
   * @param delay
   *          the delay in ms
   */
  public void delay(int delay) {
    if (timer != null) {
      timer.cancel();
      timer.schedule(delay);
    } else {
      timer = new Timer() {
        public void run() {
          timer = null;
          listener.execute();
        }
      };
      timer.schedule(delay);
    }
  }

}